<template>
    <section class="component-box">
        <h3>用户报表</h3>
        <el-select v-model="type" placeholder="请选择">
            <el-option value="year" label="本年"/>
            <el-option value="month" label="本月"/>
            <el-option value="week" label="最近七天"/>
        </el-select>
        <p>当年、当月、最近七天用户注册数报表</p>
        <div ref="echartsRef" class="echarts"></div>
    </section>
</template>
<script lang="ts" setup>
// 步骤1：引入echarts
import * as echarts from 'echarts';
import request from "@/utils/request";
import { onMounted, ref,watch } from "vue";


// 查询什么报表
const type = ref<"year" | "month" | "week">("year");

type EChartsOption = echarts.EChartsOption;

const echartsRef = ref();

let myEcharts: any;

// 步骤4：定义图表选项和数据
const option: EChartsOption = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                // 数据名称
                data: [],
                axisTick: {
                    alignWithLabel: true
                }
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: '用户注册数',
                type: 'bar',
                barWidth: '60%',
                // 数据
                data: []
            }
        ]
    };

const handleQuery = (type:'year' | 'month' | 'week') => {
    request({url:`/echarts/queryUserList/${type}`}).then(res => {
        if (res.data.code >= 1) {
            const titleData:string[] = [];
            const data:number[] = [];
            res.data.data.forEach((item:any) => {
                titleData.push(item.name);
                data.push(item.count);
            })
            option.xAxis[0].data = titleData;
            option.series[0].data = data;
            myEcharts.setOption(option);
        }
    })
}

onMounted(() => {
    // 步骤2：获取需要渲染的dom节点（也可以使用：document.querySelector('.echarts')）
    // vue需要在onMounted中才能获取到dom节点
    const echartsDom = echartsRef.value;
    // 步骤3：初始化echarts实例
    myEcharts = echarts.init(echartsDom);
    handleQuery(type.value);
});

watch(() => type.value, () => {
    handleQuery(type.value);
})


</script>
<style lang="scss" scoped>

.el-select {
    width: 140px;
    margin: 10px 0px;
}

.echarts {
    width: 100%;
    min-width: 400px;
    height: 500px;
}
</style>